<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading" class="bulk-send-content">
      <!-- 步骤指示器 -->
      <el-steps :active="currentStep" align-center class="steps-container">
        <el-step title="选择消息类型" />
        <el-step title="编辑消息内容" />
        <el-step title="选择发送对象" />
        <el-step title="确认发送" />
      </el-steps>

      <!-- 步骤1：选择消息类型 -->
      <div v-if="currentStep === 0" class="step-content">
        <h3 class="step-title">选择消息类型</h3>
        <div class="message-types">
          <div
            v-for="type in messageTypes"
            :key="type.value"
            class="message-type-card"
            :class="{ active: form.messageType === type.value }"
            @click="selectMessageType(type.value)"
          >
            <div class="type-icon">
              <el-icon :size="32"><component :is="type.icon" /></el-icon>
            </div>
            <div class="type-info">
              <div class="type-name">{{ type.label }}</div>
              <div class="type-desc">{{ type.description }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 步骤2：编辑消息内容 -->
      <div v-if="currentStep === 1" class="step-content">
        <h3 class="step-title">编辑消息内容</h3>
        
        <!-- 文本消息 -->
        <div v-if="form.messageType === 'text'" class="message-editor">
          <el-form label-width="100px">
            <el-form-item label="消息内容" required>
              <el-input
                v-model="form.content.text"
                type="textarea"
                :rows="6"
                placeholder="请输入要发送的文本消息内容..."
                maxlength="1000"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 图片消息 -->
        <div v-if="form.messageType === 'image'" class="message-editor">
          <el-form label-width="100px">
            <el-form-item label="选择图片" required>
              <el-upload
                class="image-upload"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="handleImageSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeImageUpload"
                :show-file-list="false"
                accept="image/*"
              >
                <div v-if="form.content.imageUrl" class="image-preview">
                  <img :src="form.content.imageUrl" alt="预览图片" />
                  <div class="image-overlay">
                    <el-button type="primary" size="small">重新上传</el-button>
                  </div>
                </div>
                <div v-else class="upload-placeholder">
                  <el-icon size="50"><Plus /></el-icon>
                  <div class="upload-text">点击上传图片</div>
                  <div class="upload-tip">支持 JPG、PNG 格式，大小不超过 2MB</div>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="图片描述">
              <el-input
                v-model="form.content.imageDesc"
                placeholder="可选：为图片添加描述文字"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 链接消息 -->
        <div v-if="form.messageType === 'link'" class="message-editor">
          <el-form label-width="100px">
            <el-form-item label="链接标题" required>
              <el-input
                v-model="form.content.title"
                placeholder="请输入链接标题"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="链接地址" required>
              <el-input
                v-model="form.content.url"
                placeholder="请输入完整的链接地址，如：https://www.example.com"
              />
            </el-form-item>
            <el-form-item label="链接描述">
              <el-input
                v-model="form.content.description"
                type="textarea"
                :rows="3"
                placeholder="请输入链接描述"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="封面图片">
              <el-upload
                class="cover-upload"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="handleCoverSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeImageUpload"
                :show-file-list="false"
                accept="image/*"
              >
                <div v-if="form.content.coverUrl" class="cover-preview">
                  <img :src="form.content.coverUrl" alt="封面图片" />
                  <div class="cover-overlay">
                    <el-button type="primary" size="small">重新上传</el-button>
                  </div>
                </div>
                <div v-else class="upload-placeholder small">
                  <el-icon size="30"><Plus /></el-icon>
                  <div class="upload-text">上传封面</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 步骤3：选择发送对象 -->
      <div v-if="currentStep === 2" class="step-content">
        <h3 class="step-title">选择发送对象</h3>
        <div class="target-selection">
          <el-radio-group v-model="form.targetType" class="target-type-group">
            <el-radio label="all">发送给所有联系人</el-radio>
            <el-radio label="group">选择特定客群库</el-radio>
            <el-radio label="custom">自定义选择联系人</el-radio>
          </el-radio-group>

          <!-- 选择客群库 -->
          <div v-if="form.targetType === 'group'" class="group-selection">
            <el-select
              v-model="form.selectedGroups"
              multiple
              placeholder="请选择要发送的客群库"
              style="width: 100%"
            >
              <el-option
                v-for="group in customerGroups"
                :key="group.id"
                :label="`${group.title} (${group.people_num}人)`"
                :value="group.id"
              />
            </el-select>
          </div>

          <!-- 自定义选择联系人 -->
          <div v-if="form.targetType === 'custom'" class="custom-selection">
            <div class="contact-search">
              <el-input
                v-model="contactSearchKeyword"
                placeholder="搜索联系人"
                @input="handleContactSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="contact-list">
              <el-checkbox-group v-model="form.selectedContacts">
                <div
                  v-for="contact in filteredContacts"
                  :key="contact.id"
                  class="contact-item"
                >
                  <el-checkbox :label="contact.id">
                    {{ contact.contact_info }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>

          <!-- 发送统计 -->
          <div class="send-stats">
            <el-alert
              :title="`预计发送对象：${estimatedCount} 人`"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
        </div>
      </div>

      <!-- 步骤4：确认发送 -->
      <div v-if="currentStep === 3" class="step-content">
        <h3 class="step-title">确认发送</h3>
        <div class="confirm-content">
          <div class="confirm-section">
            <h4>消息内容预览</h4>
            <div class="message-preview">
              <div v-if="form.messageType === 'text'" class="text-preview">
                {{ form.content.text }}
              </div>
              <div v-if="form.messageType === 'image'" class="image-preview-confirm">
                <img :src="form.content.imageUrl" alt="图片消息" />
                <div v-if="form.content.imageDesc" class="image-desc">
                  {{ form.content.imageDesc }}
                </div>
              </div>
              <div v-if="form.messageType === 'link'" class="link-preview">
                <div class="link-card">
                  <div v-if="form.content.coverUrl" class="link-cover">
                    <img :src="form.content.coverUrl" alt="链接封面" />
                  </div>
                  <div class="link-info">
                    <div class="link-title">{{ form.content.title }}</div>
                    <div class="link-desc">{{ form.content.description }}</div>
                    <div class="link-url">{{ form.content.url }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="confirm-section">
            <h4>发送对象</h4>
            <div class="target-summary">
              <div v-if="form.targetType === 'all'" class="target-info">
                <el-icon><UserFilled /></el-icon>
                <span>所有联系人 ({{ totalContacts }} 人)</span>
              </div>
              <div v-if="form.targetType === 'group'" class="target-info">
                <el-icon><Collection /></el-icon>
                <span>{{ selectedGroupNames.join('、') }} ({{ estimatedCount }} 人)</span>
              </div>
              <div v-if="form.targetType === 'custom'" class="target-info">
                <el-icon><Select /></el-icon>
                <span>自定义选择 ({{ form.selectedContacts.length }} 人)</span>
              </div>
            </div>
          </div>

          <div class="confirm-section">
            <h4>发送设置</h4>
            <div class="send-settings">
              <el-form label-width="120px">
                <el-form-item label="发送时间">
                  <el-radio-group v-model="form.sendType">
                    <el-radio label="now">立即发送</el-radio>
                    <el-radio label="scheduled">定时发送</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="form.sendType === 'scheduled'" label="发送时间">
                  <el-date-picker
                    v-model="form.scheduledTime"
                    type="datetime"
                    placeholder="选择发送时间"
                    :disabled-date="disabledDate"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button
          v-if="currentStep < 3"
          type="primary"
          @click="nextStep"
          :disabled="!canNextStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentStep === 3"
          type="primary"
          @click="handleConfirmSend"
          :loading="sendLoading"
        >
          确认发送
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  ChatLineSquare, Picture, Link, Plus, Search, UserFilled, Collection, Select
} from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  customerGroups?: any[]
  totalContacts?: number
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  customerGroups: () => [],
  totalContacts: 0
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'confirm': [data: any]
}>()

// 响应式数据
const loading = ref(false)
const sendLoading = ref(false)
const currentStep = ref(0)
const contactSearchKeyword = ref('')

// 消息类型配置
const messageTypes = [
  {
    value: 'text',
    label: '文本消息',
    description: '发送纯文本消息',
    icon: 'ChatLineSquare'
  },
  {
    value: 'image',
    label: '图片消息',
    description: '发送图片消息',
    icon: 'Picture'
  },
  {
    value: 'link',
    label: '链接消息',
    description: '发送链接卡片消息',
    icon: 'Link'
  }
]

// 表单数据
const form = ref({
  messageType: '',
  content: {
    text: '',
    imageUrl: '',
    imageDesc: '',
    title: '',
    url: '',
    description: '',
    coverUrl: ''
  },
  targetType: 'all',
  selectedGroups: [] as number[],
  selectedContacts: [] as number[],
  sendType: 'now',
  scheduledTime: ''
})

// 联系人数据（模拟）
const allContacts = ref([
  { id: 1, contact_info: 'user1@example.com' },
  { id: 2, contact_info: 'user2@example.com' },
  { id: 3, contact_info: '138****1234' },
  { id: 4, contact_info: '139****5678' }
])

// 上传相关
const uploadUrl = '/api/upload'
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = ['选择消息类型', '编辑消息内容', '选择发送对象', '确认发送']
  return `群发消息 - ${titles[currentStep.value]}`
})

const filteredContacts = computed(() => {
  if (!contactSearchKeyword.value) return allContacts.value
  return allContacts.value.filter(contact =>
    contact.contact_info.toLowerCase().includes(contactSearchKeyword.value.toLowerCase())
  )
})

const selectedGroupNames = computed(() => {
  return props.customerGroups
    .filter(group => form.value.selectedGroups.includes(group.id))
    .map(group => group.title)
})

const estimatedCount = computed(() => {
  if (form.value.targetType === 'all') {
    return props.totalContacts
  } else if (form.value.targetType === 'group') {
    return props.customerGroups
      .filter(group => form.value.selectedGroups.includes(group.id))
      .reduce((sum, group) => sum + group.people_num, 0)
  } else if (form.value.targetType === 'custom') {
    return form.value.selectedContacts.length
  }
  return 0
})

const canNextStep = computed(() => {
  switch (currentStep.value) {
    case 0:
      return !!form.value.messageType
    case 1:
      if (form.value.messageType === 'text') {
        return !!form.value.content.text.trim()
      } else if (form.value.messageType === 'image') {
        return !!form.value.content.imageUrl
      } else if (form.value.messageType === 'link') {
        return !!(form.value.content.title && form.value.content.url)
      }
      return false
    case 2:
      if (form.value.targetType === 'group') {
        return form.value.selectedGroups.length > 0
      } else if (form.value.targetType === 'custom') {
        return form.value.selectedContacts.length > 0
      }
      return true
    default:
      return true
  }
})

// 方法
const selectMessageType = (type: string) => {
  form.value.messageType = type
}

const nextStep = () => {
  if (currentStep.value < 3 && canNextStep.value) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const resetForm = () => {
  currentStep.value = 0
  form.value = {
    messageType: '',
    content: {
      text: '',
      imageUrl: '',
      imageDesc: '',
      title: '',
      url: '',
      description: '',
      coverUrl: ''
    },
    targetType: 'all',
    selectedGroups: [],
    selectedContacts: [],
    sendType: 'now',
    scheduledTime: ''
  }
}

const handleContactSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}

// 文件上传处理
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!')
    return false
  }
  return true
}

const handleImageSuccess = (response: any) => {
  if (response.code === 1) {
    form.value.content.imageUrl = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

const handleCoverSuccess = (response: any) => {
  if (response.code === 1) {
    form.value.content.coverUrl = response.data.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error('封面上传失败')
  }
}

const handleUploadError = () => {
  ElMessage.error('文件上传失败，请重试')
}

const handleConfirmSend = async () => {
  try {
    sendLoading.value = true
    
    const sendData = {
      messageType: form.value.messageType,
      content: form.value.content,
      targetType: form.value.targetType,
      selectedGroups: form.value.selectedGroups,
      selectedContacts: form.value.selectedContacts,
      sendType: form.value.sendType,
      scheduledTime: form.value.scheduledTime,
      estimatedCount: estimatedCount.value
    }
    
    emit('confirm', sendData)
    ElMessage.success('发送任务已创建')
    handleClose()
  } catch (error) {
    console.error('发送失败:', error)
    ElMessage.error('发送失败，请重试')
  } finally {
    sendLoading.value = false
  }
}

// 监听弹框显示状态
watch(() => props.visible, (visible) => {
  if (!visible) {
    resetForm()
  }
})
</script>

<style scoped>
.bulk-send-content {
  min-height: 500px;
}

.steps-container {
  margin-bottom: 30px;
}

.step-content {
  padding: 20px 0;
}

.step-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 消息类型选择 */
.message-types {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.message-type-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.message-type-card:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.message-type-card.active {
  border-color: #409eff;
  background: #f0f9ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.type-icon {
  margin-right: 16px;
  color: #409eff;
}

.type-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.type-desc {
  font-size: 14px;
  color: #606266;
}

/* 消息编辑器 */
.message-editor {
  max-width: 600px;
}

/* 图片上传 */
.image-upload,
.cover-upload {
  display: block;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-placeholder.small {
  width: 120px;
  height: 80px;
}

.upload-placeholder:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.upload-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.image-preview,
.cover-preview {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
}

.cover-preview {
  width: 120px;
  height: 80px;
}

.image-preview img,
.cover-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay,
.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-overlay,
.cover-preview:hover .cover-overlay {
  opacity: 1;
}

/* 发送对象选择 */
.target-type-group {
  margin-bottom: 20px;
}

.group-selection,
.custom-selection {
  margin-top: 16px;
}

.contact-search {
  margin-bottom: 16px;
}

.contact-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
}

.contact-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.contact-item:last-child {
  border-bottom: none;
}

.send-stats {
  margin-top: 20px;
}

/* 确认发送 */
.confirm-content {
  max-width: 600px;
}

.confirm-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.confirm-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.message-preview {
  padding: 16px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.text-preview {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  white-space: pre-wrap;
}

.image-preview-confirm {
  text-align: center;
}

.image-preview-confirm img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 6px;
}

.image-desc {
  margin-top: 12px;
  font-size: 14px;
  color: #606266;
}

.link-preview {
  max-width: 300px;
}

.link-card {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  background: white;
}

.link-cover img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.link-info {
  padding: 12px;
}

.link-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.link-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  line-height: 1.4;
}

.link-url {
  font-size: 12px;
  color: #909399;
  word-break: break-all;
}

.target-summary,
.target-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.send-settings {
  background: white;
  padding: 16px;
  border-radius: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-types {
    grid-template-columns: 1fr;
  }
  
  .message-type-card {
    flex-direction: column;
    text-align: center;
  }
  
  .type-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .upload-placeholder {
    width: 100%;
    height: 150px;
  }
  
  .image-preview,
  .cover-preview {
    width: 100%;
    height: auto;
    max-width: 300px;
  }
}
</style> 